package co.edu.javeriana.aes.patrones.monopolio.cliente;

import co.edu.javeriana.aes.patrones.monopolio.message.MessageEventListener;
import co.edu.javeriana.aes.patrones.monopolio.net.ClientListener;
import co.edu.javeriana.aes.patrones.monopolio.message.Message;
import co.edu.javeriana.aes.patrones.monopolio.net.NetworkConnection;
import co.edu.javeriana.aes.patrones.monopolio.session.Session;
import co.edu.javeriana.aes.patrones.monopolio.util.exception.MonopolyException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

public class MonopolyClient extends NetworkConnection implements ClientListener {

    private Session session;
    private Set<MessageEventListener> listeners;

    public MonopolyClient()
            throws MonopolyException, UnknownHostException, IOException {
        super(new Socket("localhost", 9000));
        listeners = new HashSet<MessageEventListener>();
    }

    public void addListener(MessageEventListener listener) {
        listeners.add(listener);
    }

    public void removeListener(MessageEventListener listener) {
        listeners.remove(listener);
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        if (getSession() == null) {
            this.session = session;
        }
    }

    private void handleSessionResponse(Message message) {
        setSession(message.getSession());
    }

    @Override
    public void handleMessage(Message message) {
        switch (message.getCommand()) {
            case R_CREATE_ROOM:
            case R_GET_ROOMS:
            case R_JOIN_ROOM:
            case R_LIST_OF_ROOMS:
            case R_PLAYER_JOINED:
                for (MessageEventListener listener : listeners) {
                    listener.handleRooms(message);
                }
                break;

            case C_CHAT_MESSAGE:
                for (MessageEventListener listener : listeners) {
                    listener.handleChatMessage(message);
                }
                break;

            case F_SESSION_REQUEST:
                break;

            case F_SESSION_RESPONSE:
                handleSessionResponse(message);
                break;

            case R_GET_LIST_OF_PLAYERS:
                break;

            case R_LIST_OF_PLAYERS_RESPONSE:
                for (MessageEventListener listener : listeners) {
                    listener.handlePlayerRequest(message);
                }
                break;
        }
    }

    @Override
    public void nofifyNewMessage(Message message) {
        handleMessage(message);
    }
}
